package com.zhuhao.design_mode.structural_pattern.proxy.dynamic;

import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * jdk代理，动态代理demo
 *
 * @Author halk
 * @Date 2020/11/18 15:14
 */
public class Client {
    public static void main(String[] args) {
        TeacherDao teacherDao = new TeacherDao();
        //创建代理类，并对接口的实现类进行增强
        ProxyFactory proxyFactory = new ProxyFactory(teacherDao);
        ITeacherDao instance = (ITeacherDao) proxyFactory.getProxyInstance();
        instance.teach();
        instance.name("halk");
    }

    /**
     * 被代理的接口可以没有实现类，直接对接口进行代理
     */
    @Test
    public void test() {
        ICar instance = (ICar) Proxy.newProxyInstance(
                ICar.class.getClassLoader(),
                new Class[]{ICar.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("开始代理");
                        if (args.length > 0) {
                            Object arg = args[0];
                            System.out.println("i am " + arg);
                        }
                        System.out.println("结束代理");
                        return null;
                    }
                }

        );
        instance.name("比亚迪汽车");
    }

    /**
     * 没有实现类的接口
     */
    interface ICar {
        void name(String name);
    }
}
